<%@ Import namespace="whole" %>
<%@ Import namespace="System.Web.Mail" %>
<%@ Import namespace="dammelau" %>

<script language="C#" runat="server">

void Application_OnAuthenticateRequest(Object sender, EventArgs e) {
	if( !(Request.Url.LocalPath.ToLower().IndexOf("sorry.aspx") >= 0)  ) {

		if( System.Web.HttpContext.Current.Cache["ban("+Request.ServerVariables["REMOTE_ADDR"]+")"] != null ) {
			Response.Redirect( "/sorry.aspx" );
		}
	}
}

public override string GetVaryByCustomString(HttpContext context, string arg){

	if (arg == "page") return context.Request.Url.LocalPath.ToUpper();

	if (arg == "username" && context.User.Identity.IsAuthenticated){
		HttpCookie authCookie = context.Request.Cookies[ FormsAuthentication.FormsCookieName ];
		if(null != authCookie)
		{
			FormsAuthenticationTicket authTicket = null;
			try{ authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch(Exception ex)	{ ex.ToString(); }
			if( null != authTicket )
			{
				string[] roles = authTicket.UserData.Split(new char[]{'|'});
				return roles[0];
			}
		}
	}
	if (arg == "username" && !context.User.Identity.IsAuthenticated){
		return context.Session.SessionID;
	}

	if (arg == "login.cacheIfNotLogged" && !context.User.Identity.IsAuthenticated){
		return context.Session.SessionID;
	}else	if (arg == "login.cacheIfNotLogged" && context.User.Identity.IsAuthenticated){
		try{
			Random rdm = new Random(unchecked((int)DateTime.Now.Ticks));

			string rndm = Convert.ToChar(rdm.Next(65,90))
										+ DateTime.Now.Year.ToString()
										+ DateTime.Now.DayOfYear.ToString()
										+ DateTime.Now.Hour.ToString()
										+ DateTime.Now.Minute.ToString()
										+ DateTime.Now.Second.ToString()
										+ DateTime.Now.Millisecond.ToString()
										+ Convert.ToChar(rdm.Next(65,90));
			return rndm;
		}catch(Exception e){
			return e.ToString();
		}
	}

  return "";
}

protected void Application_Error(Object sender, EventArgs e){
    if (ConfigurationManager.AppSettings["systemIs"] == "offline")
        Response.Redirect(ConfigurationManager.AppSettings["outOfOrder"]);

	try{

        if (ConfigurationManager.AppSettings["notifyErrors"] != "true")
            return;
                
		sqlUtil sqlu = new    sqlUtil();
		usrUtil usru = new    usrUtil(System.Web.HttpContext.Current.ApplicationInstance);
        int errorid = -1;

        string SQLcmd = "exec adm_insertException @url='" + Request.RawUrl.Replace("'", "''")
                                                    + "',@source='" + Server.GetLastError().Source.Replace("'", "''")
                                                    + "',@info='" + Server.GetLastError().Message.Replace("'", "''")
                                                    + "',@userid='" + usru.userid.ToString().Replace("'", "''") + "'"
                                                    ;

        errorid = Convert.ToInt32( sqlu.executeText( SQLcmd ) );

        System.Net.Mail.MailMessage mailmsg = new System.Net.Mail.MailMessage();

        mailmsg.From = new System.Net.Mail.MailAddress("dammela.it <ilpostino@dammela.it>");

        mailmsg.To.Add( ConfigurationManager.AppSettings["notifyErrorsTo"] );
        mailmsg.Subject = ConfigurationManager.AppSettings["system"] + ":Application error nr." + errorid.ToString();

		StringBuilder mb = new StringBuilder(4*1024);;

		if( usru.isLogged )
			mb.Append( "An exception occurred while user: "+usru.nick
				+" (host "+System.Web.HttpContext.Current.Request.UserHostAddress
				+") was requesting the following page:\n" );

		mb.Append( Request.RawUrl );
		mb.Append( "\n\n" );
		mb.Append( Request.UrlReferrer );
		mb.Append( "\n\n" );
		mb.Append( Server.GetLastError().ToString() );
		mb.Append( "\n" );

		mb.Append( "Message: " + Server.GetLastError().Message );
		mb.Append( "\n\n" );
		mb.Append( "Stack Trace: " + Server.GetLastError().StackTrace );
		mb.Append( "\n\n" );

        //mb.Append( "\n\n" );
        //mb.Append("SQLcmd: " + SQLcmd );
        //mb.Append( "\n\n" );
        
        mailmsg.Body = mb.ToString();
        mailmsg.BodyEncoding = Encoding.UTF8;//.ASCII;
        mailmsg.IsBodyHtml = false;

        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["justlocal.mailserver"]);
        client.Send(mailmsg);
        
		if( !(Request.RawUrl.ToLower().IndexOf("ohmygod.aspx") >= 0) )
			Response.Redirect("/help/ohmygod.aspx?errorid=" + errorid );

	}catch{
	}
}

</script>